#pragma once
#include <iostream>
#include <unordered_map>
#include <string>
#include <fstream>
#include "Log.hpp"


namespace dict_ns
{
    const std::string defaultpath = "./dict.txt";
    const std::string sep = "：";

    class Dict{
    private:
        bool Load(){
            std::ifstream in(_dict_conf_filepath);
            if(!in.is_open()){
                LOG(FATAL, "open %s error", _dict_conf_filepath.c_str());
                return false;
            }
            std::string line;
            while(std::getline(in, line)){
                if(line.empty()) continue;
                auto pos = line.find(sep);
                if(pos == std::string::npos) continue;
                std::string word = line.substr(0, pos);
                if(word.empty()) continue;
                std::string Chinese_txt = line.substr(pos + 1, line.size() - pos - 1);
                //std::string Chinese_txt = line.substr(pos + 1);
                if(Chinese_txt.empty()) continue;
                LOG(DEBUG, "loda info: %s：%s", word.c_str(), Chinese_txt.c_str());
                _dict[word] = Chinese_txt;
                //_dict.insert(std::make_pair(word, Chinese_txt));
            }
            in.close();
            LOG(DEBUG, "LOAD SUCCESS: %s", _dict_conf_filepath.c_str());
            return true;
        }
    
    public:
        Dict(const std::string& path = defaultpath):_dict_conf_filepath(path){
            Load();
        }

        std::string Translate(const std::string& word){
            auto it = _dict.find(word);
            if(it == _dict.end()){
                return  "目前词典还未有此单词，请敬请等待";
            }
            return it->second;
        }
        ~Dict(){}
    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _dict_conf_filepath;
    };
}
